import xml.etree.ElementTree as ET
import os,sys
import tkinter as tk

from tkinter import messagebox



def GetFileNameInfo(xmlFile:str)->list:
    ret=[]
    fn=os.path.basename(xmlFile).split('.')[0]
    tempP='100mmps(20um)_800_4_250Khz.xml'
    arr=fn.split('_')
    ret.append(arr[0].split('mm')[0])
    ret.append(arr[1])
    ret.append(arr[2])
    ret.append(arr[3].split('Khz')[0])
    return ret
    pass

def modifyXml(srcxmlFile:str,dstdir:str,speed:float,M:int,N:int,freq:int):
    # 解析XML文件
    tree = ET.parse(srcxmlFile)
    root = tree.getroot()

    node1='inter0'
    node2='inter1'

    # 修改节点属性
    for country in root.findall(node1):
        country.set('data', '0x00'+hex(M&0xff)[2:])
    for country in root.findall(node2):
        country.set('data', '0x00'+hex((N-1)<<2|M>>8)[2:].rjust(2,'0'))
    
    # 保存修改
    # arr= GetFileNameInfo(xmlFile)
    # 100mmps(20um)_800_4_250Khz.xml
    bn=f'{speed}mmps(20um)_{M}_{N}_{freq}Khz.xml'
    bn=f'{dstdir}\\{bn}'
    tree.write(bn,encoding='utf-8')
    return bn



def InsertTextToFile(fp:str,memo:list):
    lst=[]
    lst.extend(memo)
    with open(fp,'r') as r:
        lst.extend(r.readlines())
    
    with open(fp,'w') as w:
        w.writelines(lst)


def Get_MN_Val(mag:int, vel:float, tdiFreq:float, axis_encode = 20, x_freq = 4):

    # (int, int) Get_MN(int mag, double vel, double tdiFreq, int axis_encode = 20, int x_freq = 4)
    # {
    #     int M = 0; int N = 0;
    #     if (tdiFreq / (vel * mag) != 20 * 10) throw new Exception("tdi频率和速度不匹配");

    #     var midVal = tdiFreq / (vel / axis_encode * 1000) * x_freq;//插值
    #     List<dynamic> lst = new List<dynamic>();
    #     for (int i = 1; i < 9; i++)
    #     {
    #         lst.Add(new { n = i, m = midVal * i, jd = 1 / (midVal * i) });
    #     }
    #     var result = lst.Min(c => c.jd - 0.002);
    #     M = Convert.ToInt32(result.m);
    #     N = Convert.ToInt32(result.n);
    #     return (M, N);
    # }

    if tdiFreq / (vel * mag) != 20 * 10:
         raise Exception("tdi频率和速度不匹配")
    midVal = tdiFreq / (vel / axis_encode * 1000) * x_freq #插值
    nlist=[x for x in range(1,9,1)]

    lst=[]
    for i in nlist:
        lst.append({'n':i,'m':midVal*i,'jd':abs(1/(midVal*i)-0.002)})


    result=min(lst,key= lambda c:c['jd'])

    m=int(result['m'])
    n=result['n']

    return (m,n)


def Get_MN(mag:int, vel:float,axis_encode = 20, x_freq = 4):

    # if tdiFreq / (vel * mag) != 20 * 10:
    #      raise Exception("tdi频率和速度不匹配")
    
    tdiFreq=200*vel*mag
    midVal = tdiFreq / (vel / axis_encode * 1000) * x_freq #插值
    # print(f'midval:{midVal}')
    nlist=[x for x in range(1,9,1)]

    lst=[]
    for i in nlist:
        lst.append({'n':i,'m':midVal*i,'jd':abs(1/(midVal*i)-0.002)})

    result=min(lst,key= lambda c:c['jd'])

    m=int(result['m'])
    n=result['n']
    freq=int(tdiFreq/1000)

    return (m,n,freq)



if __name__=="__main__":
    # mag=50
    # vel=25
    # re=Get_MN(mag,vel)# M N freq
    # print(re)
    # exit()

    model_path=f'{os.path.dirname(__file__)}\\1.xml'
    # dstdir=f'{os.path.abspath('..')}'
    dstdir=f'{os.path.dirname(os.path.dirname(__file__))}'

    print(model_path,dstdir)
    #model_path=r'd:\1.xml'
    #dstdir=f"d:\\"

    # root = tk.Tk()
    # root.withdraw()  # 隐藏主窗口
    # messagebox.showinfo("测试", f'{model_path}\r\n{dstdir}')
    # root.destroy()

    # print(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
    # dstfn=modifyXml(model_path,dstdir,vel,re[0],re[1],re[2])
    dstfn=modifyXml(model_path,dstdir,float(sys.argv[1]),int(sys.argv[2]),int(sys.argv[3]),int(sys.argv[4]))
    # dstfn=modifyXml(model_path,dstdir,25, 800, 1, 250)




    head=[]
    head.append('<?xml version="1.0" encoding="UTF-8"?>'+'\n')
    head.append('<?chip_gen version="2" aversion="2" adate="20240312"?>'+'\n')
    InsertTextToFile(dstfn,head)



